package com.lengxf.mqtt.config.inbound;

import com.lengxf.mqtt.config.MqttConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

@Slf4j
@Configuration
@AllArgsConstructor
public class MqttInboundConfiguration {

    private final MqttConfiguration mqttConfiguration;
    private final MqttPahoClientFactory mqttPahoClientFactory;
    private final MessageChannel inbound;


    @Bean
    public MqttPahoMessageDrivenChannelAdapter mqttInboundAdapter() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttConfiguration.getClientName() + "_consumer_" + System.currentTimeMillis(),
                mqttPahoClientFactory, mqttConfiguration.getInboundTopic());
        DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
        converter.setPayloadAsBytes(true);
        adapter.setConverter(converter);
        adapter.setQos(0);
        adapter.setOutputChannel(inbound);
        return adapter;
    }

}
